package com.example.demo.controller;


import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
@RequestMapping(value = "/hello")
public class TestController {
    @RequestMapping(value = "/test")
    public String test(){
//    url:  http://localhost:8080/hello/test
//    返回的是html页面名称
        return "index";
    }
    @RequestMapping(value = "/dog")
    public String getDog(){
//    url:  http://localhost:8080/hello/test
//    返回的是html页面名称
        return "dog";
    }

    //http://localhost:8080/hello/excel
    @RequestMapping(value = "/excel")
    public void excel(){
        String filename="test";

        //定义一个新的工作簿
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建一个Sheet页
        XSSFSheet sheet = wb.createSheet("Sheet1");
        XSSFRow row0 = sheet.createRow(0);
        XSSFCell row01 = row0.createCell(0);
        row01.setCellValue("苹果");
        XSSFCell row02 = row0.createCell(1);
        row02.setCellValue("苹果");

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        // 使用项目根目录, 文件名加上时间戳
        String path = System.getProperty("user.dir") + "\\" + filename + dateFormat.format(date) + ".xlsx";
        System.out.println("Excel文件输出路径: " + path);
        try {
            File file = new File(path);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            wb.write(fileOutputStream);

            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
